package cn.it.service.impl;

import cn.it.dao.PermissionDao;
import cn.it.dao.RoleDao;
import cn.it.dao.UserDao;
import cn.it.pojo.Permission;
import cn.it.pojo.Role;
import cn.it.pojo.User;
import cn.it.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //查询用户基本信息，不包含用户的角色
        User user = userDao.findByUsername(username);

        if (user == null) {
            return null;
        }

        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            //根据角色ID查询关联的权限
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            //让角色关联权限
            role.setPermissions(permissions);
        }
        //让用户关联角色

        user.setRoles(roles);
        return user;
    }

    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    @Override
    public void edit(Integer[] roleIds, User user) {

        userDao.edit(user);

        Integer userId = user.getId();

        userDao.deleteUserId(userId);

        for (Integer roleId : roleIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("user_id", userId);
            map.put("role_id", roleId);
            userDao.setUserAndUserRole(map);
        }
    }

    @Override
    public void deleteById(Integer id) {

        userDao.deleteUserAndroleId(id);

        userDao.deleteById(id);

    }
}
